<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Login extends Controller_Base_Frontend {

    public function action_index() {
        $this->view->body->content = Login::view(isset($_GET["redirect"]) ? $_GET["redirect"] : '');
        $this->response->body($this->view);
    }

    public function action_login() {
        try {
            if (Model_User::login($_POST['email'], $_POST['password'])) {
                if (isset($_POST["redirect"]) && !empty($_POST["redirect"])) {
                    $redirect = $_POST["redirect"];
                } else {
                    if (Model_User::logged_in('admin')) {
                        $redirect = "adm";
                    } else {
                        $redirect = "/";
                    }
                }
//                                CORRIGIR METODO DE REDIRECIONAMENTO
//                                //version 3.3.0 redirect doesn't work, no errors...
//                                HTTP::redirect( 'dashboard/index' , 302 );
//
//                                //OR (from controller)
//                                $this->redirect( 'dashboard/index' , 302 );
                die(URL::site($redirect));
                HTTP::redirect(URL::site($redirect), 302);
                $this->redirect("http://www.google.com/", 302);
                die("lalala" + URL::base() + "/");
//                                old redirect:
//				Request::current()->redirect($redirect);
            } else {
                $errors = array("login" => __("Invalid login"));
                $this->response->body(Json_View::factory(array("content" => $errors)));
            }
        } catch (HTTP_Exception_Redirect $e) {
            // just rethrow it
            throw $e;
        } catch (Exception $e) {
            $errors = array("_external" => array("Login" => $e->getMessage()));
//            $this->template->errors[] = $e->getMessage();
            $this->response->body(Json_View::factory(array("content" => $errors)));
        }
    }

    public function action_logout() {
        Model_User::logout();
        Request::current()->redirect('/');
    }

}

// End Login